package com.lhx.wechat.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.lhx.wechat.utils.WechatMessageUtil;
import com.lhx.wechat.utils.WechatSignUtil;

/**
 *
 * 微信消息接收控制器
 */
@WebServlet("/callServlet")
public class WeixinCallServlet extends HttpServlet {

	private static final long serialVersionUID = 1L;

	private static Logger log = LoggerFactory.getLogger(WeixinCallServlet.class);

	@Override
	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		// 微信加密签名
		String signature = request.getParameter("signature");
		// 时间戳
		String timestamp = request.getParameter("timestamp");
		// 随机数
		String nonce = request.getParameter("nonce");
		// 随机字符串
		String echostr = request.getParameter("echostr");

		PrintWriter out = response.getWriter();
		// 通过检验signature对请求进行校验，若校验成功则原样返回echostr，表示接入成功，否则接入失败
		if (WechatSignUtil.checkSignature(signature, timestamp, nonce)) {
			out.print(echostr);
		}
		out.flush();
		out.close();

		System.out.println("===========do get===========");
	}

	@Override
	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		// 将请求、响应的编码均设置为UTF-8（防止中文乱码）
		request.setCharacterEncoding("UTF-8");
		response.setContentType("html/xml,charset=utf-8");

		// 调用核心业务类接收消息、处理消息
		String respMessage = this.buildResponseMsg(request);

		// 响应消息
		PrintWriter out = response.getWriter();
		out.print(respMessage);

		out.flush();
		out.close();
	}

	private String buildResponseMsg(HttpServletRequest request) {

		try {
			// xml请求解析
			Map<String, String> requestMap = WechatMessageUtil.parseXml(request.getInputStream(), false);

			// 发送方帐号（open_id）
			String fromUserName = requestMap.get("FromUserName");
			// 公众帐号
			String toUserName = requestMap.get("ToUserName");
			log.info("=========enter weixin :" + toUserName + ", user :" + fromUserName + "==========");

			return LhxWechatCall.getInstance().callFunction(requestMap);
		} catch (Exception e) {
			log.error(e.getMessage(), e);
			return "请求处理异常，请稍候尝试！";
		}
	}
}
